#include "list.h"
#include "thread.h"

#include <stdlib.h>
#include <stdio.h>

struct queue_thread* new_queue_thread () {
    struct queue_thread *qt = malloc (sizeof(struct queue_thread));
    qt->first = NULL;
    qt->last = NULL;
    return qt;
}

thread_t get_first_thread (const struct queue_thread *q) {
	if (q == NULL || q->first == NULL) return NULL;
	return q->first;
}

thread_t extract_first_thread (struct queue_thread *q) {
	if (q == NULL || q->first == NULL) return NULL;
	thread_t ret = q->first;
	q->first = q->first->next;
	ret->next = NULL;
	return ret;
}

void add_thread (struct queue_thread *q, thread_t t) {
	if (q == NULL) return;
	else if (q->first == NULL) { // 0 elements
	    t->next = NULL;
	    q->first = t;
	    q->last = t;
	}
    else { // >= 1 elements
        if (t->priority < q->first->priority) {
            t->next = q->first;
            q->first = t;
        }
        else if (t->priority >= q->last->priority) {
            q->last->next = t;
	        q->last = t;
        }
        else {
            thread_t prev = q->first;
	        thread_t curr = q->first->next;
	        while (curr != q->last) {
	            if (t->priority < curr->priority) {
	                t->next = curr;
	                prev->next = t;
	                return;
	            }
	            prev = curr;
	            curr = curr->next;
	        }
	        if (curr == q->last) {
	            t->next = q->last;
	            prev->next = t;
	        }
        }
    }
}

void print_queue (struct queue_thread *qt) {
    if (qt == NULL || qt->first == NULL) printf("[  ]");
    else {
        printf("[ ");
        thread_t curr;
        for (curr = qt->first; curr != qt->last; curr = curr->next) {
            printf("%d ", curr->id);
        }
        if (curr == qt->last) printf("%d ", curr->id);
        printf("]");
    }
    putchar('\n');
}
